<?php


namespace app\api\model;


use app\common\library\AlimpModel;
use app\common\library\dingding\AliDingDing;
use app\common\library\IDMan;
use app\common\library\PlatformModel;
use app\common\library\TimerALModel;
use app\common\library\WxpayMoldel;
use app\common\model\BaseModel;
use think\Exception;
use think\facade\Log;
use ApiOper;
use common;

class UserPayRecord
{
    var $city_id;
    var $order_id;
    var $user_id;
    var $order_type;
    var $prepay_id;
    var $gateway;
    var $amount;
    var $order_state;
    var $transaction_id;
    var $out_order_id;
    var $payment_info;
    var $pay_city;
}

const PAY_ORDER_STATE_PREPAY = 0;
const PAY_ORDER_STATE_FINISH = 100;
const PAY_ORDER_STATE_REFUND = 101;
const PAY_ORDER_STATE_REFUND_FINISH = 200;

class PayModel extends BaseModel
{
    protected $name = 'user_pay_order';
    protected $pk = 'id';

    var $_wxpay = null;

    function __construct($city_id = null)
    {
        if (empty($city_id)){
            $this->_wxpay = config('app.wxpay');
        }
        else{
            $vxkcfg = PlatformModel::get_city_al_token($city_id);
            $this->_wxpay = $vxkcfg['wxpay'];
        }
    }

    function wx_sign($data)
    {
        ksort($data);

        $sarr = [];
        foreach ($data as $k => $v) {
            $sarr[] = "$k=$v";
        }
        $sarr[] = "key={$this->_wxpay['key']}";

        $s = implode('&', $sarr);
        //hilog::debug("wxsign =================== ", $s);
        return strtoupper(md5($s));
    }

    function wxmp_unifield_order($city_id, $order_type, $out_order_id, $amount, $body,$pay_city = 'default',$profit_sharing = false)
    {
        $order_id = IDMan::order_id();
        $userinfo = (new UserModel())->query_info(\ApiOper::instance()->userinfo()['id']);
        $wxresult = (new WxpayMoldel($pay_city))->create_wxmp_unifield_order($userinfo, $order_id, $amount, $body,$pay_city,$profit_sharing);

        Log::debug('wxmp_unifield_order result'.$wxresult);
        if (empty($wxresult)) {
            return false;
        }

        $r = new UserPayRecord();
        $r->city_id = $city_id;
        $r->order_id = $order_id;
        $r->order_type = $order_type;
        $r->out_order_id = $out_order_id;
        $r->order_state = PAY_ORDER_STATE_PREPAY;
        $r->gateway = PAY_GATEWAY_WEIXIN;
        $r->amount = $amount;
        $r->prepay_id = $wxresult['prepay_id'];
        $r->user_id = $userinfo['id'];
        $r->pay_city = $pay_city;

        $this->add_order($r);
        return $wxresult;
    }

    function wxpay_refund($out_order_info, $new_order_type, $amount)
    {
        $order_id = IDMan::order_id();
        $detail = $out_order_info['detail'];
        Log::debug('#################', $detail);
        $input = new WxPayRefund();
        $input->SetAppid($detail['appid']);
        $input->SetMch_id($detail['mch_id']);
        $input->SetOut_refund_no($order_id);
        $input->SetOp_user_id($detail['openid']);

        $input->SetTransaction_id($out_order_info['transaction_id']);
        $input->SetRefund_fee($amount);
        $input->SetTotal_fee($out_order_info['amount']);
        $input->SetNotify_url($this->_wxpay['refund_notify_url']);

        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        WxPayConfig::$NOTIFY_URL = $this->_wxpay['notify_url'];
        WxPayConfig::$APPID = $platform['appid'];
        WxPayConfig::$KEY = $this->_wxpay['key'];
        WxPayConfig::$MCHID = $this->_wxpay['mch_id'];
        WxPayConfig::$SSLCERT_PATH = $this->_wxpay['sslcert_path'];
        WxPayConfig::$SSLKEY_PATH = $this->_wxpay['sslkey_path'];

        $result = WxPayApi::refund($input);

        if (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') {
            $this->throw_myexception(X_ERROR, "退款失败，请联系客服！");
        }
        $r = new UserPayRecord();
        $r->city_id = $out_order_info['city_id'];
        $r->order_id = $order_id;
        $r->order_type = $new_order_type;
        $r->out_order_id = $out_order_info['id'];
        $r->order_state = PAY_ORDER_STATE_REFUND;
        $r->gateway = PAY_GATEWAY_WEIXIN;
        $r->amount = 0 - $amount;
        $r->prepay_id = null;
        $r->user_id = $out_order_info['user_id'];
        $this->add_order($r);
        return $r;
    }

    /*
     * app支付
     * */
    function wxapp_unifield_order($city_id, $order_type, $out_order_id, $amount, $body,$pay_city = 'default') {
        $order_id = IDMan::order_id();
        $userinfo = (new UserModel())->query_info(\ApiOper::instance()->userinfo()['id']);
        $wxresult = (new WxpayMoldel($pay_city))->create_wxapp_unifield_order($userinfo,$order_id, $amount, $body,$pay_city);

        Log::debug('wxmp_unifield_order result',$wxresult);
        if (empty($wxresult)) {
            return false;
        }

        $r = new UserPayRecord();
        $r->city_id = $city_id;
        $r->order_id = $order_id;
        $r->order_type = $order_type;
        $r->out_order_id = $out_order_id;
        $r->order_state = PAY_ORDER_STATE_PREPAY;
        $r->gateway = PAY_GATEWAY_WEIXIN;
        $r->amount = $amount;
        $r->prepay_id = $wxresult['prepay_id'];
        $r->user_id = $userinfo['id'];
        $r->pay_city = $pay_city;
        $this->add_order($r);

        return $wxresult;
    }

    /**
     * @param $r UserPayRecord
     */
    function add_order($r)
    {
        $data = [
            'city_id' => $r->city_id,
            'id' => $r->order_id,
            'order_type' => $r->order_type,
            'out_order_id' => $r->out_order_id,
            'prepay_id' => $r->prepay_id,
            'gateway' => $r->gateway,
            'amount' => $r->amount,
            'order_state' => $r->order_state,
            'create_time' => date('Y-m-d H:i:s'),
            'user_id' => $r->user_id,
            'channel' => ApiOper::instance()->userinfo()['channel'],
            'detail' => $r->payment_info,
        ];

        if (empty($r->pay_city)){
            $data['pay_city'] = 'default';
        }
        else{
            $data['pay_city'] = $r->pay_city;
        }

        self::create($data,true);
    }

    function query_info($id)
    {
        $selectlist = [
            'id' => 'string',
            'city_id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            'end_time' => 'string',
            'order_type' => 'string',
            'out_order_id' => 'string',
            'prepay_id' => 'string',
        ];


        $sfs = common::array_keys($selectlist);
        $beans = [
            'id'=>$id,
        ];

        $info = $this->where($beans)->field($sfs)->find();
        return $info;
    }

    function query_info_by_out_order_id($id)
    {
        $selectlist = [
            'id' => 'string',
            'city_id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            'end_time' => 'string',
            'order_type' => 'string',
            'out_order_id' => 'string',
            'detail' => 'array',
            'transaction_id' => 'string',
        ];


        $sfs = common::array_keys($selectlist);
        $beans = [
            'out_order_id'=>$id,
        ];

        $info = $this->where($beans)->field($sfs)->find();
        return $info;
    }

    function finish($order_id, $transaction_id, $detail)
    {
        $data = [
            'order_state' => PAY_ORDER_STATE_FINISH,
            'transaction_id' => $transaction_id,
            'end_time' => date('Y-m-d H:i:s'),
        ];

        if ($detail) {
            $data['detail'] = $detail;
        }

        $where = [
            'id' => $order_id,
        ];
        self::update($data, $where);
    }

    function query_list($cd, $pos, $limit)
    {
        $selectlist = [
            'id' => 'string',
            'user_id' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'order_type' => 'string',
            'detail' => 'array',
            'create_time' => 'string',
            'end_time' => 'string',
            'out_order_id' => 'string',
            'prepay_id' => 'string',
        ];

        $sfs = common::array_keys($selectlist);
        $beans = [
        ];
        if (isset($cd['user_id'])) {
            $beans['user_id'] = $cd['user_id'];
        }

        if (isset($cd['order_state'])) {
            $beans['order_state'] = $cd['order_state'];
        } else {
            $beans['order_state'] = ['>=',PAY_ORDER_STATE_FINISH];
        }

        if (isset($cd['gateway'])) {
            $beans['gateway'] = $cd['gateway'];
        }
        if (isset($cd['order_type'])) {
            $beans['order_type'] = $cd['order_type'];
        }

        if(isset($cd['no_order_type'])){
            $beans['order_type'] = ['<>',$cd['no_order_type']];
        }

        $rows = $this->where($beans)->field($sfs)->order('create_time','desc')->limit($pos,$limit)->select();

        return $rows->toArray();
    }

    function add_record($city_id, $user_id, $order_type, $order_id, $gateway, $amount, $detail = null)
    {
        $data = [
            'city_id' => $city_id,
            'id' => IDMan::city_order_id($city_id),
            'order_type' => $order_type,
            'out_order_id' => $order_id,
            'prepay_id' => null,
            'gateway' => $gateway,
            'amount' => $amount,
            'order_state' => PAY_ORDER_STATE_FINISH,
            'create_time' => date('Y-m-d H:i:s'),
            'user_id' => $user_id,
            'channel' => ApiOper::instance()->userinfo()['channel'],
        ];
        if (!empty($detail)) {
            $data['detail'] = $detail;
        }

        self::create( $data,true);
    }

    function wxpay_decrypt($s)
    {
        $str = base64_decode($s, true);

        $key = md5($this->_wxpay['key']);
        $req_xml_str = openssl_decrypt($str, 'aes-256-ecb', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);


        $pad = ord(substr($req_xml_str, -1));
        if ($pad < 1 || $pad > 32) {
            $pad = 0;
        }

        return substr($req_xml_str, 0, (strlen($req_xml_str) - $pad));
    }

    function alipay_create_trade($city_id, $order_type, $out_order_id, $alipay_user_id, $amount, $body,$pay_city = 'default')
    {
        $order_id = IDMan::order_id();

        $result = (new AlimpModel($pay_city))->create_trade($order_id, $alipay_user_id, $amount, $body,$pay_city);

        $r = new UserPayRecord();
        $r->city_id = $city_id;
        $r->order_id = $order_id;
        $r->order_type = $order_type;
        $r->out_order_id = $out_order_id;
        $r->order_state = PAY_ORDER_STATE_PREPAY;
        $r->gateway = PAY_GATEWAY_ALIPAY;
        $r->amount = $amount;
        $r->prepay_id = null;
        $r->user_id = ApiOper::instance()->userinfo()['id'];
        $r->pay_city = $pay_city;

        $this->add_order($r);

        return $result;
    }

    function submit_refund($out_order_id, $new_order_type, $amount, $reason,$is_profit = 0)
    {
        $out_order_info = $this->query_info_by_out_order_id($out_order_id);
        $ret = null;
        $total_amount = $out_order_info['amount'];
        if ($out_order_info['gateway'] == PAY_GATEWAY_WEIXIN) {
            if ($is_profit == 1 && $total_amount > 0){
                $profit_infos = (new SharePayRecordModel())->query_by_origin_id($out_order_id);
                if (!empty($profit_infos) && is_array($profit_infos)){
                    foreach ($profit_infos as $profit){
                        //分账成功
                        if ($profit['order_state'] == BILL_SHARE_ORDER_STATE_FAILED)
                            continue;

                        //退款数据
                        $refund_amount = round($profit['amount']/$total_amount*$amount);
                        if ($refund_amount > $profit['amount'])
                            $refund_amount = $profit['amount'];

                        $receiver = [
                            'account' => $profit['account_id'],
                            'amount' =>$refund_amount,
                            'desc' => '用户退款',
                        ];

                        $echo_share = $this->wxmp_profitshare_refund($profit['share_id'],$receiver);
                        if (!empty($echo_share)){
                            $refund_amount_total = $profit['refund_amount_total'] + $echo_share['return_amount'];
                            (new SharePayRecordModel())->update_profit_refund($profit['id'],BILL_SHARE_ORDER_STATE_REFUND_FINISHED,$echo_share['return_amount'],$refund_amount_total,$echo_share['out_return_no']);
                        }
                    }
                }
            }
            $ret = $this->wxpay_refund($out_order_info, $new_order_type, $amount);
        } else if ($out_order_info['gateway'] == PAY_GATEWAY_ALIPAY) {
            $ret = $this->alipay_refund($out_order_info, $new_order_type, $amount, $reason);

            if ($is_profit == 1 && $total_amount > 0){
                $profit_infos = (new SharePayRecordModel())->query_by_origin_id($out_order_id);
                if (!empty($profit_infos) && is_array($profit_infos)){
                    foreach ($profit_infos as $profit){
                        //退款数据
                        if ($profit['order_state'] == BILL_SHARE_ORDER_STATE_FAILED)
                            continue;

                        $refund_amount = round($profit['amount']/$total_amount * $amount);
                        if ($refund_amount > $profit['amount'])
                            $refund_amount = $profit['amount'];

                        (new SharePayRecordModel())->update_profit_refund($profit['id'],BILL_SHARE_ORDER_STATE_REFUND_FINISHED,$refund_amount,$profit['amount'],$ret->order_id);
                    }
                }
            }
        } else {
            $this->throw_myexception(E_EXCEPTION, "undefine gateway");
        }
        return $ret;
    }

    function alipay_refund($out_order_info, $new_order_type, $amount, $reason)
    {
        $order_id = IDMan::order_id();

        $result = (new AlimpModel($out_order_info['city_id']))->trade_refund($out_order_info['out_order_id'], $out_order_info['transaction_id'], $order_id, $amount, $reason);
        if (empty($result)) {
            $this->throw_myexception(X_ERROR, "退款失败，请联系管理员");
        }

        $r = new UserPayRecord();
        $r->city_id = $out_order_info['city_id'];
        $r->order_id = $order_id;
        $r->order_type = $new_order_type;
        $r->out_order_id = $out_order_info['id'];
        $r->order_state = PAY_ORDER_STATE_REFUND_FINISH;
        $r->gateway = PAY_GATEWAY_ALIPAY;
        $r->amount = 0 - $amount;
        $r->prepay_id = null;
        $r->user_id = $out_order_info['user_id'];
        $r->payment_info = $result;
        $this->add_order($r);
        return $r;
    }

    function alipay_create_trade_app($city_id, $order_type, $out_order_id, $amount, $body,$pay_city = 'default')
    {
        $order_id = IDMan::order_id();

        $result = (new AlimpModel($pay_city))->create_trade_app($order_id, $amount, $body,$pay_city);

        $r = new UserPayRecord();
        $r->city_id = $city_id;
        $r->order_id = $order_id;
        $r->order_type = $order_type;
        $r->out_order_id = $out_order_id;
        $r->order_state = PAY_ORDER_STATE_PREPAY;
        $r->gateway = PAY_GATEWAY_ALIPAY;
        $r->amount = $amount;
        $r->prepay_id = null;
        $r->user_id = ApiOper::instance()->userinfo()['id'];
        $r->pay_city = $pay_city;

        $this->add_order($r);

        return $result;
    }

    function check_alipay_order($date)
    {
        (new  AlimpModel())->download_bill($date);
    }

    function check_wxpay_order($date)
    {
        $count = (new WxpayMoldel())->query_count($date);
        if ($count == 0) {
            (new WxpayMoldel())->download_bill($date);
        }
        $this->check_wxpay_pay_order($date);
        $this->check_wxpay_refund_order($date);
    }

    function check_wxpay_pay_order($date)
    {
        $cd = [
            'start_time' => $date . " 00:00:00",
            'end_time' => $date . " 23:59:59",
            'order_state' => PAY_ORDER_STATE_PREPAY,
            'gateway' => PAY_GATEWAY_WEIXIN,
        ];
        $i = 0;
        while ($i < 200) {
            $l = $this->query_list($cd, 200 * $i++, 200);
            foreach ($l as $e) {
                try {
                    $wxpay_order_info = (new WxpayMoldel())->query_info_by_out_trade_no($e['id']);
                    //hilog::debug('user pay order info:', $e);
                    //hilog::debug('wxpay order info', $wxpay_order_info);
                    if ($e['order_state'] == 0 && $wxpay_order_info && $wxpay_order_info['result'] == 'SUCCESS') {
                        //支付成功，为完成充值或会员卡订单
                        if ($e['order_type'] == ORDER_TYPE_USER_CHARGE) {
                            (new UserChargeModel())->finish($e['out_order_id'], $e);
                            $userinfo = (new UserModel())->query_info($e['user_id']);
                            (new WxmpMsg())->send_msg_charge($userinfo['wxmp_open_id'], $e['prepay_id'], $e['amount'], $userinfo['balance']);

                            (new PayModel())->finish($e['id'], $wxpay_order_info['trade_no'], $wxpay_order_info);
                        } else if ($e['order_type'] == ORDER_TYPE_USER_MEMBER_SHIP) {
                            (new UserMembershipOrderModel())->finish($e['out_order_id'], $wxpay_order_info);
                            (new PayModel())->finish($e['id'], $wxpay_order_info['trade_no'], $wxpay_order_info);
                        } else if ($e['order_type'] == ORDER_TYPE_USER_RIDE_CHARGE) {
                            (new UserChargeRideOrderModel())->finish($e['out_order_id'], $wxpay_order_info);
                            (new PayModel())->finish($e['id'], $wxpay_order_info['trade_no'], $wxpay_order_info);
                        }

                    } else {
                        $data = [
                            'order_state' => -1,
                        ];
                        $where = [
                            'id' => $e['id'],
                        ];
                        self::update($data, $where);
                    }
                } catch (Exception $ex) {
                    Log::error("check wxpay bill", $ex->getMessage());
                }
            }
            if (count($l) < 200) {
                break;
            }
        }
    }

    function check_wxpay_refund_order($date)
    {
        $count = (new WxpayMoldel())->query_count($date);
        if ($count == 0) {
            (new WxpayMoldel())->download_bill($date);
        }
        $cd = [
            'start_time' => $date . " 00:00:00",
            'end_time' => $date . " 23:59:59",
            'order_state' => PAY_ORDER_STATE_REFUND,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'order_type' => ORDER_TYPE_USER_CHARGE_REFUND,
        ];

        $i = 0;
        while ($i < 200) {
            $l = $this->query_list($cd, 200 * $i++, 200);
            foreach ($l as $e) {
                try {
                    $wxpay_refund_order_info = (new WxpayMoldel())->query_info_by_out_trade_no($e['out_order_id']);
                    if ($e['order_state'] == 0 && $wxpay_refund_order_info && $wxpay_refund_order_info['result'] == 'REFUND') {
                        $pay_order_info = $this->query_info($e['out_order_id']);

                        if ($e['order_type'] == ORDER_TYPE_USER_CHARGE_REFUND) {
                            (new UserChargeModel())->refund_finish($pay_order_info['out_order_id'], null);
                            (new PayModel())->finish($e['id'], $wxpay_refund_order_info['refund_trade_no'], null);
                        } else if ($e['order_type'] == ORDER_TYPE_USER_MEMBER_SHIP_REFUND) {
                            (new UserMembershipOrderModel())->refund_finish($pay_order_info['out_order_id'], null);
                            (new PayModel())->finish($e['id'], $wxpay_refund_order_info['refund_trade_no'], null);
                        } else if ($e['order_type'] == ORDER_TYPE_USER_RIDE_CHARGE_REFUND) {
                            (new UserChargeRideOrderModel())->refund_finish($pay_order_info['out_order_id'], null);
                            (new PayModel())->finish($e['id'], $wxpay_refund_order_info['refund_trade_no'], null);
                        }
                    } else {
                        $logStr = "核对退款订单异常，URI：" . $_SERVER['HTTP_HOST'] . ", 订单ID：" . $e['id'];
                        $ding = new AliDingDing(config('app.system_warning_ding_ding_token'));
                        $ding->assign('text', $logStr)
                            ->at(true)
                            ->send();
                    }
                } catch (Exception $ex) {
                    Log::error("check wxpay bill", $ex->getMessage());
                }
            }
            if (count($l) < 200) {
                break;
            }
        }
    }


    /**分账
     * @param $gate_way
     * @param $city_id
     * @param $orgin_id
     * @param $order_type
     * @param $total_amount
     * @param $transaction_id
     * @return array|bool|mixed|SimpleXMLElement|null
     */
    function profitshare_order($gate_way, $city_id, $orgin_id, $order_type, $total_amount, $transaction_id)
    {
        $config = PlatformModel::get_city_profit_config($gate_way,$city_id);
        Log::info('profitshare_order',$config);
        if (empty($config))
            return null;

        //暂定数值修改
        if ($order_type == ORDER_TYPE_USER_RIDE_CHARGE){
            $info = (new UserChargeRideOrderModel())->query_info($orgin_id);
            if (!empty($info)){
                //分账的时候可能已经退款了，数值不对
                if ($info['order_state'] >= USER_CHARGERIDE_ORDER_STATE_REFUND){
                    $total_amount = $info['amount'] - $info['refund_amount'];
                }
            }
        }

        if ($total_amount <=0)
            return null;

        $receivers = [
            [
                'account'=>$config['account'],
                'amount' => floor($total_amount * $config['amount']*0.99),
                'desc' => $config['desc'],
            ]
        ];

        if ($gate_way == PAY_GATEWAY_ALIPAY) {
            return $this->alipay_profitshare_order($city_id,$orgin_id, $order_type, $total_amount, $transaction_id, $receivers);
        }
        elseif($gate_way == PAY_GATEWAY_WEIXIN) {
            return $this->wxmp_profitshare_order($city_id, $orgin_id,$order_type, $total_amount, $transaction_id, $receivers);
        }
        else
            return null;
    }


    /**微信分账
     * @param $city_id
     * @param $orgin_id
     * @param $order_type
     * @param $total_amount
     * @param $transaction_id
     * @param $receivers array[
     * [
     *  'amount' => 1,
     *  'account' => 1600817902,
     *  'desc' => '数据'
     * ]
     * @return array|bool|null
     */
    function wxmp_profitshare_order($city_id, $orgin_id, $order_type, $total_amount, $transaction_id, $receivers)
    {
        $order_id = IDMan::city_order_id($city_id);
        $wxresult = (new WxpayMoldel())->create_wxprofitshare_order($order_id,$transaction_id, $receivers);

        Log::debug('wxprofitshare result', $wxresult);
        if (empty($wxresult)) {
            //拆分数据
            foreach ($receivers as $receiver){
                (new SharePayRecordModel())->add_order($city_id,$orgin_id,$total_amount,$receiver,$order_type,PAY_GATEWAY_WEIXIN,$transaction_id,$order_id,null,BILL_SHARE_ORDER_STATE_FAILED);
            }
            return false;
        }

        if (isset($wxresult['order_id'])){
            $share_id = $wxresult['order_id'];

            //拆分数据
            foreach ($receivers as $receiver){
                (new SharePayRecordModel())->add_order($city_id,$orgin_id,$total_amount,$receiver,$order_type,PAY_GATEWAY_WEIXIN,$transaction_id,$order_id,$share_id,BILL_SHARE_ORDER_STATE_FINISHED);
            }
        }

        return $wxresult;
    }


    /**支付宝分账
     * @param $city_id
     * @param $orgin_id
     * @param $order_type
     * @param $total_amount
     * @param $transaction_id
     * @param $receivers
     * @return array|bool|mixed|SimpleXMLElement|null
     */
    function alipay_profitshare_order($city_id, $orgin_id, $order_type, $total_amount, $transaction_id, $receivers)
    {
        $order_id = IDMan::city_order_id($city_id);
        $wxresult = (new AlimpModel())->create_settle_request($order_id,$transaction_id,$receivers);

        if (isset($wxresult['trade_no'])){
            $share_id = $wxresult['trade_no'];

            //拆分数据
            foreach ($receivers as $receiver){
                (new SharePayRecordModel())->add_order($city_id,$orgin_id,$total_amount,$receiver,$order_type,PAY_GATEWAY_ALIPAY,$transaction_id,$order_id,$share_id,BILL_SHARE_ORDER_STATE_FINISHED);
            }
        }
        else{
            foreach ($receivers as $receiver){
                (new SharePayRecordModel())->add_order($city_id,$orgin_id,$total_amount,$receiver,$order_type,PAY_GATEWAY_ALIPAY,$transaction_id,$order_id,null,BILL_SHARE_ORDER_STATE_FAILED);
            }
        }

        return $wxresult;
    }

    //分账退款
    function wxmp_profitshare_refund($out_order_id,$receiver)
    {
        $order_id = IDMan::order_id();


        $input = new WxPayProfitShareRefund();
        $input->SetOrderId($out_order_id);

        $input->SetOut_return_no($order_id);
        $input->SetReturn_account_type('MERCHANT_ID');
        $input->SetReturn_account($receiver['account']);
        $input->SetReturn_amount($receiver['amount']);
        $input->SetDescription($receiver['desc']);

        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        WxPayConfig::$NOTIFY_URL = $this->_wxpay['notify_url'];
        WxPayConfig::$APPID = $platform['appid'];
        WxPayConfig::$KEY = $this->_wxpay['key'];
        WxPayConfig::$MCHID = $this->_wxpay['mch_id'];
        WxPayConfig::$SSLCERT_PATH = $this->_wxpay['sslcert_path'];
        WxPayConfig::$SSLKEY_PATH = $this->_wxpay['sslkey_path'];

        $result = WxPayApi::profit_share_refund($input);
        if (empty($result)){
            $this->throw_myexception(X_ERROR, "退款失败，请联系客服！");
        }


        if (!isset($result['result']) || $result['result'] == 'FAILED') {
            $this->throw_myexception(X_ERROR, "退款失败，请联系客服！");
        }

        return $result;
    }

    //分账请求
    function timer_profitshare($city_id,$amount,$trans_id,$order_type,$gate_way,$orgin_id)
    {
        //分账
        $path = '/wallet/profit_notify';

        $params = [
            'token' => 'SUOZHANGBIEKAIQIANG',
            'city_id' => $city_id,
            'total_amount' => $amount,
            'transaction_id' => $trans_id,
            'order_type' => $order_type,
            'gate_way' => $gate_way,
            'origin_id' => $orgin_id
        ];

        TimerALModel::instance()->call_bus_server($path, $params, 180);
    }
}